package demo.spark.stream.format;

import org.apache.hadoop.io.BytesWritable;

import java.lang.reflect.Field;
import java.util.stream.Stream;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2021/9/9 上午11:25
 * @UpdateDate:
 * @Description:
 */
public class LengthUnfixedBytesWritable extends BytesWritable{

    private static final Field size;
    private static final Field bytes;

    static {
        Field sizeField = null;
        Field bytesField = null;
        try {
            sizeField = BytesWritable.class.getDeclaredField("size");
            bytesField = BytesWritable.class.getDeclaredField("bytes");
            sizeField.setAccessible(true);
            bytesField.setAccessible(true);
        }catch (Throwable e){
            e.printStackTrace();
        }
        size = sizeField;
        bytes = bytesField;
    }

    /**
     * To change super's byte buffer and length by reflect.
     * @param newBytes
     */
    public void updateBytes(byte[] newBytes){
        try {
            bytes.set(this,newBytes);
            size.set(this,newBytes.length);
        }catch (Throwable e){
            e.printStackTrace();
        }
    }
}